﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;

namespace Lswweb.Domain
{
    internal class PaymentService
    {
        public SortedDictionary<string, string> parameters;

        public PaymentService(string paymentGateway)
        {
            this.PaymentGateway = paymentGateway;

            this.FormName="payment";
            this.RequestMethod = Domain.RequestMethod.Post;

            this.parameters = new SortedDictionary<string, string>();
        }

        /// <summary>
        /// 付款提交表单name
        /// </summary>
        public string FormName { get; set; }

        /// <summary>
        /// 在线支付接口Url
        /// Paypal：https://www.paypal.com/cgi-bin/webscr
        /// Paypal模拟测试：https://www.sandbox.paypal.com/cgi-bin/webscr
        /// 支付宝：https://www.alipay.com/cooperate/gateway.do
        /// </summary>
        public string PaymentGateway { get; private set; }

        /// <summary>
        /// 表单请求方式：Post/Get
        /// 默认值：Post
        /// </summary>
        public RequestMethod RequestMethod { get; set; }

        /// <summary>
        /// 支付表请求参数集合
        /// </summary>
        public SortedDictionary<string, string> PaymentParameters { get { return this.parameters; } }

        public string BuilderFormHTML()
        {
            StringBuilder builderHtml = new StringBuilder();

            builderHtml.Append(string.Format(
                "<form id=\"{0}\" name=\"{0}\" action=\"{1}\" method=\"{2}\">Loading...",
                this.FormName,
                this.PaymentGateway,
                this.RequestMethod));

            foreach (KeyValuePair<string, string> item in PaymentParameters)
            {
                builderHtml.Append(string.Format(
                    "<input type=\"hidden\" name=\"{0}\" value=\"{1}\"/>",
                    item.Key,
                    item.Value));
            }

            //submit按钮控件请不要含有name属性
            builderHtml.Append("<input type=\"submit\" style=\"display:none;\" value=\"Payment\"></form>");

            builderHtml.Append(string.Format(
                 "<script>document.forms['{0}'].submit();</script>",
                 this.FormName));

            return builderHtml.ToString();
        }
    }
}
